//
//  CommodityDetailViewController.m
//  BabyAndBabyDriver
//
//  Created by 范琦 on 16/8/15.
//  Copyright © 2016年 范琦. All rights reserved.
//

#import "CommodityDetailViewController.h"
#import "HarvestDetailCell.h"
#import "DetailCell.h"
#import "HarvestShopCell.h"
#import "JSONKit.h"
#import "MBProgressHUD.h"

@interface CommodityDetailViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    MBProgressHUD *hud;
}

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *listArr1;
@property (nonatomic, strong) NSMutableArray *listArr2;
@property (nonatomic, strong) NSMutableArray *allList;

@property (nonatomic, assign) BOOL isSelect;
@property (nonatomic, strong) UILabel *moneyLabel;
@property (nonatomic, assign) CGFloat money;
@property (nonatomic, strong) NSMutableDictionary *ceshiDic;


@end

@implementation CommodityDetailViewController

- (void)viewWillAppear:(BOOL)animated
{

    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;


}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"订单详情";
    self.listArr1 = [NSMutableArray arrayWithObjects:@"商户名称:测试商户", @"地址:测试地址", @"电话:15840840610", @"收款方式:余额", nil];
    
    self.listArr2 = [NSMutableArray array];
    self.isSelect = YES;
    
    [self creatTableView];
    if ([_str isEqualToString:@"添加"] || [_str isEqualToString:@"未完成"] || [_str isEqualToString:@"商品添加"] || [_str isEqualToString:@"商品未完成"] ) {
        [self creatOtherView1];
    }else{
    
        [self creatOtherView];
    }
    
    if ([_str isEqualToString:@"商品添加"]) {
        
        self.listArr1 = [NSMutableArray arrayWithObjects:
                         [NSString stringWithFormat:@"商户名称: %@",_addDic[@"name_merchant"]],
                         [NSString stringWithFormat:@"联系人: %@",_addDic[@"name"]],
                         [NSString stringWithFormat:@"电话: %@",_addDic[@"user_name"]],
                         [NSString stringWithFormat:@"地址: %@",_addDic[@"address"]],
                         nil];
        
        [self netHandleShop];
        
        
    }
    else{
    
        if ([_str isEqualToString:@"添加"]) {
            NSDictionary *dic = self.addDic[@"user"];
            self.listArr1 = [NSMutableArray arrayWithObjects:[NSString stringWithFormat:@"商户名称:%@", dic[@"name_merchant"]], [NSString stringWithFormat:@"地址:%@", dic[@"address"]], [NSString stringWithFormat:@"电话:%@", dic[@"user_name"]], [NSString stringWithFormat:@"收款方式:%@", _style], nil];
            
            _allList = [NSMutableArray arrayWithArray:_addDic[@"category"]];
            for (int i = 0; i<_allList.count; i++) {
                NSDictionary *dic = [NSDictionary dictionary];
                [_listArr2 addObject:dic];
            }
            
            
        }else if(![_str isEqualToString:@"入库"]){
            [self netHandle];
            
        }else{
            [self netHandleRuku];
            
        }
        
    }
}


- (void)netHandleShop
{
    YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:@"Mall/goodsList" paramDic:@{@"token":TOKEN} RegisterApiMethod:RequestMethodGet];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSDictionary *dic = request.responseBody[@"result"];
        self.ceshiDic = [NSMutableDictionary dictionaryWithDictionary:request.responseBody[@"result"]];
        
        _allList = [NSMutableArray arrayWithArray:dic[@"goods"]];
        for (int i = 0; i<_allList.count; i++) {
            NSDictionary *dic = [NSDictionary dictionary];
            [_listArr2 addObject:dic];
        }
        [_tableView reloadData];
        [self getMoney];
        
    } failure:nil];
}
- (void)netHandle
{
    YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:@"Order/detailAn" paramDic:@{@"token":TOKEN, @"id":_myId} RegisterApiMethod:RequestMethodPost];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSDictionary *dic = request.responseBody[@"result"];
        if ([dic[@"is_recycling_man_pay"] integerValue] == 1) {
            
            self.listArr1 = [NSMutableArray arrayWithObjects:[NSString stringWithFormat:@"商户名称:%@", dic[@"name_merchant"]], [NSString stringWithFormat:@"地址:%@", dic[@"address"]], [NSString stringWithFormat:@"电话:%@", dic[@"tel"]], [NSString stringWithFormat:@"收款方式:%@", @"现金" ], nil];
            _style = @"现金";
        }else{
        self.listArr1 = [NSMutableArray arrayWithObjects:[NSString stringWithFormat:@"商户名称:%@", dic[@"name_merchant"]], [NSString stringWithFormat:@"地址:%@", dic[@"address"]], [NSString stringWithFormat:@"电话:%@", dic[@"tel"]], [NSString stringWithFormat:@"收款方式:%@", @"余额" ], nil];
            _style = @"余额";
        }
        self.ceshiDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        
        _allList = [NSMutableArray arrayWithArray:dic[@"goods"]];
        for (int i = 0; i<_allList.count; i++) {
            NSDictionary *dic = [NSDictionary dictionary];
            [_listArr2 addObject:dic];
        }
        [_tableView reloadData];
        [self getMoney];
        
    } failure:nil];
}
- (void)netHandleRuku
{
    YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:@"StroageInput/detail" paramDic:@{@"token":TOKEN, @"id":_myId} RegisterApiMethod:RequestMethodPost];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSDictionary *dic = request.responseBody[@"result"];
        
            self.listArr1 = [NSMutableArray arrayWithObjects:[NSString stringWithFormat:@"入库单号:%@", dic[@"code"]], [NSString stringWithFormat:@"入库时间:%@", dic[@"create_datetime"]], [NSString stringWithFormat:@"佣金:%@", dic[@"commission"]], nil];
     
        _allList = [NSMutableArray arrayWithArray:dic[@"goods"]];
        for (int i = 0; i<_allList.count; i++) {
            NSDictionary *dic = [NSDictionary dictionary];
            [_listArr2 addObject:dic];
        }
        [_tableView reloadData];
        _moneyLabel.text = [NSString stringWithFormat:@"实收款:%@", dic[@"commission"]];

    } failure:nil];
}
- (void)creatOtherView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, KSCREENHEIGHT - 104, KSCREENWIDTH, 1)];
    view.backgroundColor = TEXTCOLOR;
    [self.view addSubview:view];
    
    self.moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(KSCREENWIDTH - 150, KSCREENHEIGHT - 104, 130, 40)];
    _moneyLabel.text = @"0.0元";
    _moneyLabel.textColor = [UIColor redColor];
    _moneyLabel.textAlignment = NSTextAlignmentRight;
    _moneyLabel.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:_moneyLabel];
}
- (void)creatOtherView1
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, KSCREENHEIGHT - 154, KSCREENWIDTH, 1)];
    view.backgroundColor = TEXTCOLOR;
    [self.view addSubview:view];
    
    self.moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(KSCREENWIDTH - 150, KSCREENHEIGHT - 154, 130, 40)];
    _moneyLabel.text = @"实收款: 0元";
    _moneyLabel.textColor = [UIColor redColor];
    _moneyLabel.textAlignment = NSTextAlignmentRight;
    _moneyLabel.font = [UIFont systemFontOfSize:13];
    
    [self.view addSubview:_moneyLabel];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(20, KSCREENHEIGHT - 114, KSCREENWIDTH - 40, 40);
    btn.backgroundColor = BACKGROUNDCOLOR;
    [btn setTitle:@"成功" forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:btn];
    btn.tintColor = [UIColor whiteColor];
    btn.layer.cornerRadius = 5;
    
    if ([_str isEqualToString:@"商品添加"]) {
        
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            
            [_ceshiDic setObject:_allList forKey:@"goods"];
            NSString *str = [_ceshiDic JSONString];
            
            YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:@"Mall/merchantConfirm" paramDic:@{@"token":TOKEN, @"uid":_addDic[@"id"], @"data":str} RegisterApiMethod:RequestMethodPost];
            [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                
                if ([request.responseBody[@"error"] integerValue] == 0) {
                    [self hud:request.responseBody[@"result"]];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
                
                
            } failure:nil];
            
            NSLog(@"失败");
            
            
        }];
    }else if ([_str isEqualToString:@"添加"]){
    
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:_addDic];
            [dic setObject:_allList forKey:@"category"];
            NSString *str = [dic JSONString];
            
            YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:@"Order/merchantConfirm" paramDic:@{@"token":TOKEN, @"uid":_addDic[@"user"][@"id"], @"data":str,@"is_recycling_man_pay" : _style} RegisterApiMethod:RequestMethodPost];
            [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                
                if ([request.responseBody[@"error"] integerValue] == 0) {
                    [self hud:@"添加成功"];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }else{
                
                    [self hud:request.responseBody[@"msg"]];

                }
                
                
            } failure:nil];
            
            NSLog(@"失败");
            
            
        }];
    
    }else{
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:_addDic];
            [dic setObject:_allList forKey:@"goods"];
            NSString *str = [dic JSONString];
            
            YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:@"Order/ok.json" paramDic:@{@"token":TOKEN, @"id":_ceshiDic[@"id"], @"data":str} RegisterApiMethod:RequestMethodPost];
            [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                
                if ([request.responseBody[@"error"] integerValue] == 0) {
                    [self hud:@"确认成功"];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }else{
                    
                    [self hud:request.responseBody[@"msg"]];
                    
                }
                
                
            } failure:nil];
            
            NSLog(@"失败");
            
            
        }];

    
    
    
    }

}
- (void)creatTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT - 155) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 50;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [_tableView registerNib:[UINib nibWithNibName:@"HarvestDetailCell" bundle:nil] forCellReuseIdentifier:@"cell1"];
    [_tableView registerNib:[UINib nibWithNibName:@"DetailCell" bundle:nil] forCellReuseIdentifier:@"cell2"];
    [_tableView registerNib:[UINib nibWithNibName:@"HarvestShopCell" bundle:nil] forCellReuseIdentifier:@"cell3"];

    [self.view addSubview:_tableView];
    
    _tableView.showsVerticalScrollIndicator = NO;
    
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _allList.count + 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    return 35;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return _listArr1.count;
    }
    if (_listArr2.count != 0) {
        
        NSDictionary *dic = _listArr2[section - 1];
        NSArray *arr = dic[@"children"];
        return arr.count;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 35)];
    view.backgroundColor = [UIColor whiteColor];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    
        NSDictionary *dic = _allList[section - 1];
        
        
        [btn setTitle:dic[@"name"] forState:UIControlStateNormal];
        

    [view addSubview:btn];
    btn.tintColor = BACKGROUNDCOLOR;
    btn.frame = CGRectMake(15, 0, 100, 35);
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
       
        
        [_listArr2 removeAllObjects];
        for (int i = 0; i<_allList.count; i++) {
            NSDictionary *dic = [NSDictionary dictionary];
            [_listArr2 addObject:dic];
        }
        
        NSDictionary *dic = _allList[section - 1];
        [_listArr2 replaceObjectAtIndex:section - 1 withObject:dic];
        
        [_tableView reloadData];
        
    }];
    return view;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:13];
        cell.textLabel.textColor = [UIColor colorWithRed:141/255.0 green:141/255.0 blue:141/255.0 alpha:1];
        cell.textLabel.text = _listArr1[indexPath.row];
        
        return cell;
    }else{
        if ([_str isEqualToString:@"添加"] || [_str isEqualToString:@"未完成"] || [_str isEqualToString:@"商品添加"]) {
            DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:_listArr2[indexPath.section - 1]];
            NSMutableArray *arr = [NSMutableArray arrayWithArray:dic[@"children"]];
            NSMutableDictionary *result = [NSMutableDictionary dictionaryWithDictionary:arr[indexPath.row]];
            cell.title.text = result[@"name"];
            cell.money.text = [NSString stringWithFormat:@"%@/%@", result[@"price"], result[@"unit"]];
            if ([_str isEqualToString:@"商品添加"]) {
                NSString *str = [[result[@"name"] componentsSeparatedByString:@"/"] lastObject];
                
                cell.money.text = [NSString stringWithFormat:@"%@/%@", result[@"price"], [str substringToIndex:1]];
            }
            cell.number.text = result[@"unit"];
            cell.text.text = [result[@"qty"] stringValue];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [[[cell.addBtn rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(id x) {
                
                NSInteger i = [result[@"qty"] integerValue];
                [result setObject:[NSNumber numberWithInteger:i + 1] forKey:@"qty"];
                [arr replaceObjectAtIndex:indexPath.row withObject:result];
                [dic setObject:arr forKey:@"children"];
                [_listArr2 replaceObjectAtIndex:indexPath.section - 1 withObject:dic];
                [_allList replaceObjectAtIndex:indexPath.section - 1 withObject:dic];
                [_tableView reloadData];
                [self getMoney];
            
            }];
            
            [[[cell.reduceBtn rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(id x) {
                NSInteger i  = [result[@"qty"] integerValue];
                if (i > 0) {
                    
                    [result setObject:[NSNumber numberWithInteger:i - 1] forKey:@"qty"];
                    [arr replaceObjectAtIndex:indexPath.row withObject:result];
                    [dic setObject:arr forKey:@"children"];
                    [_listArr2 replaceObjectAtIndex:indexPath.section - 1 withObject:dic];
                    [_allList replaceObjectAtIndex:indexPath.section - 1 withObject:dic];
                    [_tableView reloadData];
                    [self getMoney];
                }
                
            }];
            
            [[cell.text rac_signalForControlEvents:UIControlEventEditingDidEnd] subscribeNext:^(id x) {
               
                NSInteger i  = [cell.text.text integerValue];
                if (i > 0) {
                    
                    [result setObject:[NSNumber numberWithInteger:i] forKey:@"qty"];
                    [arr replaceObjectAtIndex:indexPath.row withObject:result];
                    [dic setObject:arr forKey:@"children"];
                    [_listArr2 replaceObjectAtIndex:indexPath.section - 1 withObject:dic];
                    [_allList replaceObjectAtIndex:indexPath.section - 1 withObject:dic];
                    [_tableView reloadData];
                    [self getMoney];
                }else{
                    cell.text.text = @"0";
                }
                
                
                
            }];
            
            return cell;
        }
        else if(![_str isEqualToString:@"入库"]){
        
        
            HarvestDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:_listArr2[indexPath.section - 1]];
            NSMutableArray *arr = [NSMutableArray arrayWithArray:dic[@"children"]];
            NSMutableDictionary *result = [NSMutableDictionary dictionaryWithDictionary:arr[indexPath.row]];
            cell.title.text = result[@"name"];
            cell.money.text = [NSString stringWithFormat:@"%@/%@", result[@"price"], result[@"unit"]];
            cell.number.text = [NSString stringWithFormat:@"%ld %@", [result[@"qty"] integerValue], result[@"unit"]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else{
            HarvestShopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:_listArr2[indexPath.section - 1]];
            NSMutableArray *arr = [NSMutableArray arrayWithArray:dic[@"children"]];
            NSMutableDictionary *result = [NSMutableDictionary dictionaryWithDictionary:arr[indexPath.row]];
            cell.title.text = result[@"name"];
            cell.number.text = [NSString stringWithFormat:@"%ld %@", [result[@"qty"] integerValue], result[@"unit"]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
}
// 计算总金额
- (void)getMoney
{
    _money = 0;

    for (NSDictionary *dic in _allList) {
        
        NSArray *arr = dic[@"children"];
        for (NSDictionary *dic in arr) {
            
            NSInteger i = [dic[@"qty"] integerValue];
            CGFloat f = i * [dic[@"price"] floatValue];
            _money += f;
        }
    }
    _moneyLabel.text = [NSString stringWithFormat:@"实收款:%.2lf元",_money];

}
- (void)hud:(NSString *)str
{
    
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    hud = [[MBProgressHUD alloc] initWithWindow:window];
    hud.removeFromSuperViewOnHide = YES;
    
    [window addSubview:hud];
    hud.labelText = str;
    hud.labelColor = [UIColor colorWithHexString:@"#A1A1AC"];
    hud.labelFont = [UIFont systemFontOfSize:15];
    hud.mode = MBProgressHUDModeCustomView;
    hud.progress = 0;
    
    [hud show:YES];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(hiden) userInfo:nil repeats:NO];
}
- (void)hiden
{
    [hud hide:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
